package com.lei.leetcode;

import java.util.*;

/**
 * @Author LeiXiaoLei
 * @Date 2022/8/18 19:02
 * @Version 1.0
 */
public class S_1224 {

    public int maxEqualFreq1(int[] nums) {
        //以nums = [2,2,1,1,5,3,3,5]为例
        int [] cnt=new int [100010];//统计某数字出现的个数，如cnt[1]=2
        int [] cntsum=new int [100010];//出现了i次的数字的个数,如cntsum[2]=4
        int maxcnt=0;//最大出现次数
        int prelen=0;//当前遍历到的前缀长度
        int n=nums.length;
        int res=0;
        for(int i=0;i<n;i++){
            int num=nums[i];
            int cur=++cnt[num];
            maxcnt=Math.max(maxcnt,cur);
            cntsum[cur]++;
            cntsum[cur-1]--;//假设原本统计得某数出现次数为1，更新后变成了2，也说明出现次数为1的那个要减一个了
            prelen=i+1;
            if((maxcnt==1)||(maxcnt*cntsum[maxcnt]==prelen-1)||((maxcnt-1)*(cntsum[maxcnt-1]+1)==prelen-1)) res=prelen;
        }
        return res;
    }
    public static int maxEqualFreq(int[] nums) {
        List<Integer> list = diffNum(nums);
        return getMax(list);
    }

    private static int getMax(List<Integer> list) {
        int res = 0;
        if (list.size() == 1) return list.get(0);
        if (list.size() == 2) return list.get(0) + list.get(1);
        for (int i = 0; i < list.size(); ) {
            if (list.get(0) == 1) {
                i++;
            } else if (i + 2 < list.size()) {
                if (res < list.get(i) + list.get(1 + 2)) res = list.get(i) + list.get(i + 2);
                i = i + 2;
            } else i++;
        }

        return res;
    }

    private static List<Integer> diffNum(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int count;
        int n = 0;
        int temp;
        for (int i = 0; i < nums.length; ) {
            count = 0;
            temp = nums[i];
            while (temp == nums[i]) {
                count++;
                i++;
                if (i >= nums.length) {
                    break;
                }
            }
            list.add(count);
        }
        return list;
    }

    public static void main(String[] args) {
        int[] nums = {2,2,1,1,5,3,3,5};
        int i = maxEqualFreq(nums);
        System.out.println(i);
    }
}
